// 服务模块主文件

// 重新导出所有服务
pub mod memory;
pub use memory::*;

pub mod process;
pub use process::*;

pub mod filesystem;
pub use filesystem::*;

pub mod network;
pub use network::*;

pub mod ipc;
pub use ipc::*;

// 服务管理器实现
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use log::{info, error};
use crate::core::{Service, ServiceStatus, ServiceManager as CoreServiceManager};

/// KUKU服务管理器
pub struct KukuServiceManager {
    services: HashMap<String, Arc<Mutex<dyn Service>>>,
}

impl KukuServiceManager {
    pub fn new() -> Self {
        KukuServiceManager {
            services: HashMap::new(),
        }
    }

    /// 注册服务
    pub fn register_service(&mut self, name: String, service: Arc<Mutex<dyn Service>>) -> Result<(), String> {
        if self.services.contains_key(&name) {
            return Err(format!("Service '{}' already registered", name));
        }
        
        info!("Registering service: {}", name);
        self.services.insert(name, service);
        Ok(())
    }

    /// 启动服务
    pub fn start_service(&self, name: &str) -> Result<(), String> {
        if let Some(service) = self.services.get(name) {
            let mut service = service.lock().map_err(|e| format!("Failed to lock service: {}", e))?;
            service.start()
        } else {
            Err(format!("Service '{}' not found", name))
        }
    }

    /// 停止服务
    pub fn stop_service(&self, name: &str) -> Result<(), String> {
        if let Some(service) = self.services.get(name) {
            let mut service = service.lock().map_err(|e| format!("Failed to lock service: {}", e))?;
            service.stop()
        } else {
            Err(format!("Service '{}' not found", name))
        }
    }

    /// 获取服务状态
    pub fn get_service_status(&self, name: &str) -> Option<ServiceStatus> {
        self.services.get(name).and_then(|service| {
            service.lock().ok().map(|s| s.status())
        })
    }

    /// 列出所有服务
    pub fn list_services(&self) -> Vec<String> {
        self.services.keys().cloned().collect()
    }

    /// 启动所有服务
    pub fn start_all_services(&self) -> Result<(), String> {
        info!("Starting all registered services...");
        
        for name in self.services.keys() {
            if let Err(err) = self.start_service(name) {
                error!("Failed to start service '{}': {}", name, err);
                return Err(format!("Failed to start service '{}': {}", name, err));
            }
        }
        
        info!("All services started successfully");
        Ok(())
    }

    /// 停止所有服务
    pub fn stop_all_services(&self) -> Result<(), String> {
        info!("Stopping all registered services...");
        
        for name in self.services.keys() {
            if let Err(err) = self.stop_service(name) {
                error!("Failed to stop service '{}': {}", name, err);
                return Err(format!("Failed to stop service '{}': {}", name, err));
            }
        }
        
        info!("All services stopped successfully");
        Ok(())
    }
}

impl CoreServiceManager for KukuServiceManager {
    fn register_service(&mut self, service: Arc<Mutex<dyn Service>>) -> Result<(), String> {
        // 从服务中获取名称
        let name = service.lock().map_err(|e| format!("Failed to lock service: {}", e))?.name();
        self.register_service(name.to_string(), service)
    }

    fn start_service(&self, name: &str) -> Result<(), String> {
        self.start_service(name)
    }

    fn stop_service(&self, name: &str) -> Result<(), String> {
        self.stop_service(name)
    }

    fn get_service_status(&self, name: &str) -> Option<ServiceStatus> {
        self.get_service_status(name)
    }

    fn list_services(&self) -> Vec<String> {
        self.list_services()
    }
}

/// 服务工厂 - 用于创建各种服务实例
pub struct ServiceFactory;

impl ServiceFactory {
    /// 创建内存服务
    pub fn create_memory_service(_capability: Arc<()>) -> Result<Arc<Mutex<dyn Service>>, String> {
        let service = memory::MemoryService::new(Arc::new(()))?;
        Ok(Arc::new(Mutex::new(service)))
    }

    /// 创建进程服务
    pub fn create_process_service() -> Result<Arc<Mutex<dyn Service>>, String> {
        let service = process::ProcessService::new()?;
        Ok(Arc::new(Mutex::new(service)))
    }

    /// 创建文件系统服务
    pub fn create_filesystem_service() -> Result<Arc<Mutex<dyn Service>>, String> {
        let service = filesystem::FileSystemService::new()?;
        Ok(Arc::new(Mutex::new(service)))
    }

    /// 创建网络服务
    pub fn create_network_service() -> Result<Arc<Mutex<dyn Service>>, String> {
        let service = network::NetworkService::new()?;
        Ok(Arc::new(Mutex::new(service)))
    }

    /// 创建IPC服务
    pub fn create_ipc_service() -> Result<Arc<Mutex<dyn Service>>, String> {
        let service = ipc::IPCService::new()?;
        Ok(Arc::new(Mutex::new(service)))
    }

    /// 创建默认服务集合
    pub fn create_default_services() -> Result<HashMap<String, Arc<Mutex<dyn Service>>>, String> {
        let mut services = HashMap::new();
        
        // 创建进程服务
        if let Ok(service) = Self::create_process_service() {
            services.insert("process".to_string(), service);
        }
        
        // 创建文件系统服务
        if let Ok(service) = Self::create_filesystem_service() {
            services.insert("filesystem".to_string(), service);
        }
        
        // 创建网络服务
        if let Ok(service) = Self::create_network_service() {
            services.insert("network".to_string(), service);
        }
        
        // 创建IPC服务
        if let Ok(service) = Self::create_ipc_service() {
            services.insert("ipc".to_string(), service);
        }
        
        Ok(services)
    }
}